package com.hsmw.schedule.utils;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.hsmw.domain.vo.GpsInfoEntity;
import com.hsmw.domain.vo.PageListDTO;
import com.hsmw.domain.vo.TrajectoryDTO;
import lombok.Data;
import lombok.NoArgsConstructor;
import okhttp3.*;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.*;

@Component
public class NewGPSUtils {


    private static HashMap tokenHub = new HashMap<>();

    private static final MediaType mediaType = MediaType.parse("application/json; charset=utf-8");


    private static final MediaType formType = MediaType.parse("application/x-www-form-urlencoded; charset=utf-8");

    //GPS
    private static final String ID = "NTgzLjI3ODYuNjA1";

    private static final String secret = "abd5158b1d167350b2b1dfe9b4736b6e";

    private static String Authorization = "";

    //获取登录用户下所有客户
    private static final String clientrUrl = "http://39.100.230.2:8083/video/client/tree";

    // login
    private static final String loginrUrl = "http://39.100.230.2:8083/video/user/api/login";


    private static final String vehicleUrl = "http://39.100.230.2:8083/video/vehicle/simple/list";

    //4.获取里程统计接口
    private static final String mileageUrl = "http://39.100.230.2:8083/video/report/query";

    //获取里程明细接口
    private static final String mileageDetailUrl = "http://39.100.230.2:8083/video/report/mileageStatistics";

    //11.获取实时位置接口
    private static final String vehicleDatalUrl = "http://39.100.230.2:8083/video/monitor/getVehicleDataByIds";

    // 10.轨迹回放接口
    private static final String TrajectoryUrl = "http://39.100.230.2:8083/video/trajectory/guijilist";


    /**
     * 查看公司下所有的车辆信息
     *
     * @param url
     * @param json
     * @return
     */
    public static List responseInfo(HashMap<String, String> paramsMap) {

        List<Map<String, Object>> list = new ArrayList<>();

        Map<String, Object> map = new HashMap<>();
        String token = getAccessToken();

        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        JSONObject json = JSONUtil.parseFromMap(paramsMap);
        RequestBody body = RequestBody.create(mediaType, json.toString());
        Request request = new Request.Builder()
                .url(vehicleUrl)
                .post(body)
                .addHeader("Authorization", token)
                .addHeader("Content-Type", "application/json")
                .build();
        try {
            Response response = client.newCall(request).execute();
            JSONObject responses = JSONUtil.parseObj(response.body().string());
            if (responses.getStr("message").contains("成功")) {
                JSONArray data = responses.getJSONArray("data");
                for (int i = 0; i < data.size(); i++) {
                    JSONObject dataJSONObject = data.getJSONObject(i);
                    String vehicleTypeName = dataJSONObject.getStr("vehicleTypeName");
                    String vehicleId = dataJSONObject.getStr("vehicleId");
                    String vehicleName = dataJSONObject.getStr("vehicleName");
                    map.put("vehicleId", vehicleId);
                    map.put("vehicleName", vehicleName);
                    map.put("vehicleTypeName", vehicleTypeName);
                    list.add(map);
                }
            }
            return list;

        } catch (IOException e) {
            e.printStackTrace();
            return list;
        }
    }


    /***
     * login 获取token
     * @param paramsMap
     * @return
     */
    public static String login() {

        HashMap<String, String> paramsMap = new HashMap<String, String>();
        OkHttpClient mOkHttpClient = new OkHttpClient();
        FormBody.Builder formBodyBuilder = new FormBody.Builder();
        paramsMap.put("key", ID);
        paramsMap.put("secret", secret);
        Set<String> keySet = paramsMap.keySet();
        for (String key : keySet) {
            String value = paramsMap.get(key);
            formBodyBuilder.add(key, value);
        }
        FormBody formBody = formBodyBuilder.build();
        Request request = new Request
                .Builder()
                .post(formBody)
                .url(loginrUrl)
                .build();
        try (Response response = mOkHttpClient.newCall(request).execute()) {
            JSONObject jsonObject = JSONUtil.parseObj(response.body().string());
            JSONObject data = jsonObject.getJSONObject("data");
            String token = data.getStr("token");
            return token;
        } catch (Exception e) {
            e.printStackTrace();
            return "err";
        }

    }


    public static String getAccessToken() {
        if (tokenHub.size() == 0) {
            String token = login();
            tokenHub.put("createTime", new Date());
            tokenHub.put("token", token);
            return token;
        } else {
            Date createTime = (Date) tokenHub.get("createTime");
            Long now = System.currentTimeMillis();

            if (now - createTime.getTime() >= 86400000) {
                //如果创建时间大于7200s 则过期了，需要重新生成
                String newToken = login();
                tokenHub.put("createTime", new Date());
                tokenHub.put("token", newToken);
                return newToken;
            } else {
                return (String) tokenHub.get("token");
            }
        }
    }


    /**
     * 历程统计
     *
     * @param paramsMap
     * @return
     */
    public static List<PageListDTO> findVehicleMileageStatisticsByVehicleid(HashMap<String, String> paramsMap) {

        List<PageListDTO> list = null;
        String token = getAccessToken();

        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        JSONObject json = JSONUtil.parseFromMap(paramsMap);
        RequestBody body = RequestBody.create(mediaType, json.toString());
        Request request = new Request.Builder()
                .url(mileageUrl)
                .post(body)
                .addHeader("Authorization", token)
                .addHeader("Content-Type", "application/json")
                .build();
        try {
            Response response = client.newCall(request).execute();
            JSONObject responses = JSONUtil.parseObj(response.body().string());
            if (responses.getStr("message").contains("成功")) {
                JSONObject data = responses.getJSONObject("data");
                JSONArray pageList = data.getJSONArray("pageList");
                list = JSONUtil.toList(pageList, PageListDTO.class);
            }
            return list;

        } catch (IOException e) {
            e.printStackTrace();
            return list;
        }
    }


    /**
     * .获取里程明细接口
     *
     * @param paramsMap
     * @return
     */
    public static List findVehicleMileageDetailByVehicleid(HashMap<String, String> paramsMap) {

        List<PageListDTO> list = null;
        Map<String, Object> map = new HashMap<>();
        String token = getAccessToken();

        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        JSONObject json = JSONUtil.parseFromMap(paramsMap);
        RequestBody body = RequestBody.create(mediaType, json.toString());
        Request request = new Request.Builder()
                .url(mileageDetailUrl)
                .post(body)
                .addHeader("Authorization", token)
                .addHeader("Content-Type", "application/json")
                .build();
        try {
            Response response = client.newCall(request).execute();
            JSONObject responses = JSONUtil.parseObj(response.body().string());
            if (responses.getStr("message").contains("成功")) {
                JSONObject data = responses.getJSONObject("data");
                JSONArray pageList = data.getJSONArray("pageList");
                list = JSONUtil.toList(pageList, PageListDTO.class);
            }
            return list;

        } catch (IOException e) {
            e.printStackTrace();
            return list;
        }

    }

    /**
     * 车辆实时位置
     * ids 车辆id 多个车辆进行拼接 （41767,42306）
     * @param paramsMap
     * @return
     */
    public static List<GpsInfoEntity> getVehicleDataByIds(HashMap<String, String> paramsMap) {

        Long start = System.currentTimeMillis();
        List<GpsInfoEntity> list = new ArrayList<>();

        OkHttpClient mOkHttpClient = new OkHttpClient();
        FormBody.Builder formBodyBuilder = new FormBody.Builder();
        Set<String> keySet = paramsMap.keySet();
        for (String key : keySet) {
            String value = paramsMap.get(key);
            formBodyBuilder.add(key, value);
        }
        String token = getAccessToken();
        FormBody formBody = formBodyBuilder.build();
        Request request = new Request
                .Builder()
                .post(formBody)
                .url(vehicleDatalUrl)
                .addHeader("Authorization", token)
                .addHeader("Content-Type", "application/json")
                .build();

        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        JSONObject json = JSONUtil.parseFromMap(paramsMap);
        RequestBody body = RequestBody.create(mediaType, json.toString());
        try {
            Response response = mOkHttpClient.newCall(request).execute();
            JSONObject responses = JSONUtil.parseObj(response.body().string());
            if (responses.getStr("message").contains("成功")) {
                JSONArray data = responses.getJSONArray("data");
                for (int i = 0; i < data.size(); i++) {
                    JSONObject obj = data.getJSONObject(i);
                    if (data != null) {
                        GpsInfoEntity gpsInfoEntity = new GpsInfoEntity();
                        gpsInfoEntity.setGpsLon(obj.getStr("lng"));
                        gpsInfoEntity.setGpsLat(obj.getStr("lat"));
                        gpsInfoEntity.setDeviceId(obj.getStr("vehicle_id"));
                        Boolean online = obj.getBool("online");
                        if(online){
                            gpsInfoEntity.setIsOnline("1");
                        }else {
                            gpsInfoEntity.setIsOnline("0");
                        }
                        gpsInfoEntity.setRcvTime(obj.getStr("recvtime"));
                        gpsInfoEntity.setDirect(obj.getStr("dir"));
                        gpsInfoEntity.setAdree(obj.getStr("adree"));
                        list.add(gpsInfoEntity);
                    }
                }
            }
            System.out.println("xin gps 请求时间"+(System.currentTimeMillis()-start));
            return list;

        } catch (IOException e) {
            e.printStackTrace();
            return list;
        }

    }


    /**
     * 轨迹回放
     * @param paramsMap
     * vid 车辆id
     * Strattime 开始时间 年于日时分秒 格式
     * endtime 结束时间
     * av 无效数据 0 不过滤 1 过滤
     * bufa 补发数据 0 不过滤 1 过滤
     * orderNo 排序 0 服务器时间 1 卫星时间
     * tingchedian 停车数据 0 不过滤 1 过滤
     * @return
     */
    public static List<TrajectoryDTO> getVehicleTrajectoryById(HashMap<String, String> paramsMap) {

        List<TrajectoryDTO> list = new ArrayList<>();

        OkHttpClient mOkHttpClient = new OkHttpClient();
        FormBody.Builder formBodyBuilder = new FormBody.Builder();
        Set<String> keySet = paramsMap.keySet();
        for (String key : keySet) {
            String value = paramsMap.get(key);
            formBodyBuilder.add(key, value);
        }
        String token = getAccessToken();
        FormBody formBody = formBodyBuilder.build();
        Request request = new Request
                .Builder()
                .post(formBody)
                .url(TrajectoryUrl)
                .addHeader("Authorization", token)
                .addHeader("Content-Type", "application/json")
                .build();

        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        JSONObject json = JSONUtil.parseFromMap(paramsMap);
        RequestBody body = RequestBody.create(formType, json.toString());
        try {
            Response response = mOkHttpClient.newCall(request).execute();
            JSONObject responses = JSONUtil.parseObj(response.body().string());
            if (responses.getStr("message").contains("成功")) {
                JSONArray data = responses.getJSONArray("data");
                list = JSONUtil.toList(data, TrajectoryDTO.class);
            }
            return list;

        } catch (IOException e) {
            e.printStackTrace();
            return list;
        }

    }






    public static void main(String[] args) {
        HashMap<String, String> map = new HashMap<>();
        map.put("Strattime", "2021-11-01 00:00:00");
        map.put("endtime", "2021-11-01 05:59:59");
        map.put("av", "1");
        map.put("bufa", "1");
        map.put("orderNo", "1");
        map.put("tingchedian", "1");
        map.put("vid", "30160");
        List<TrajectoryDTO> vehicleDataByIds = getVehicleTrajectoryById(map);
      /*  for (TrajectoryDTO vehicleDataById : vehicleDataByIds) {

            System.err.println(vehicleDataById.toString());
        }*/

        HashMap<String, String> map1 = new HashMap<>();
        map1.put("ids", "45300");
        System.out.println(getVehicleDataByIds(map1));


    }
}
